<?php

namespace App\Services\Stats\User;

use App\Models\Game\Log\UserLogin;
use App\Models\Game\Settlement\Info;
use App\Models\Game\User\User;
use App\Services\Service;
use App\Services\Stats\User\Elasticsearch\EsPlayerService;
use App\Services\Traits\DatabaseMysql;
use App\Models\Admin\Stats\User\Day;
use App\Models\Admin\Stats\User\Week;
use App\Models\Admin\Stats\User\Month;
use Helper\Timed;

class PlayerService extends Service
{
	use DatabaseMysql;

	/**
	 * 统计图【天】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @return array
	 */
	public function day($request)
	{
		$datetime = $request->input('datetime');

		return $this->stats($request, 'day', $datetime[0], $datetime[1]);
	}

	/**
	 * 统计图【周】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @return array
	 */
	public function week($request)
	{
		date_default_timezone_set(Timed::getTimezoneName());

		$datetime = $request->input('datetime');

		$datetime = strtotime(date('Y-01-01', $datetime));

		return $this->stats(
			$request,'week', $datetime, strtotime('+1 year', $datetime)
		);
	}

	/**
	 * 统计图【月】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @return array
	 */
	public function month($request)
	{
		$datetime = $request->input('datetime');

		return $this->stats($request,'month', $datetime[0], $datetime[1]);
	}

	/**
	 * 获取统计数据
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param \Illuminate\Database\Query\Builder $query
	 * @param int $timed
	 * @param int $timedEnd
	 * @return array
	 */
	protected function stats($request, $group_day, $start_time, $end_time)
	{
		$timezone = Timed::getTimeCode();

		// 查询数据
		$selectUGame = $selectUSign = $selectNuGame = $selectNuSign =  '';
		$group_time = '';
		switch ($group_day){
			case 'day':
				$group_time = '1d';
				$selectUGame = "DATE(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(end_time), '%Y-%m-%d %H:%i:%s'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) as timed";
				$selectUSign = "DATE(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(login_time), '%Y-%m-%d %H:%i:%s'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) as timed";
				$selectNuGame  = "DATE(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(first_game_time), '%Y-%m-%d %H:%i:%s'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) as timed";
				$selectNuSign  = "DATE(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(registration_time), '%Y-%m-%d %H:%i:%s'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) as timed";
				break;
			case 'week':
				$group_time = '1w';
				$selectUGame = "WEEK(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(end_time), '%Y-%m-%d'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) AS timed";
				$selectUSign = "WEEK(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(login_time), '%Y-%m-%d'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) AS timed";
				$selectNuGame  = "WEEK(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(first_game_time), '%Y-%m-%d'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) AS timed";
				$selectNuSign  = "WEEK(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(registration_time), '%Y-%m-%d'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) AS timed";
				break;
			case 'month':
				$group_time = '1M';
				$selectUGame = "DATE_FORMAT(CONVERT_TZ(FROM_UNIXTIME(end_time), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."'), '%Y-%m-01') AS timed";
				$selectUSign = "DATE_FORMAT(CONVERT_TZ(FROM_UNIXTIME(login_time), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."'), '%Y-%m-01') AS timed";
				$selectNuGame = "DATE_FORMAT(CONVERT_TZ(FROM_UNIXTIME(first_game_time), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."'), '%Y-%m-01') AS timed";
				$selectNuSign = "DATE_FORMAT(CONVERT_TZ(FROM_UNIXTIME(registration_time), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."'), '%Y-%m-01') AS timed";
				break;

		}

		if (!!config('elasticsearch.default')) {
			$esPlayerService = new EsPlayerService();
			$stats_u_game = $esPlayerService->u_game($request, $group_time, $start_time, $end_time);
			$stats_u_sign = $esPlayerService->u_sign($request, $group_time, $start_time, $end_time);
		}else{
			$stats_u_game = $this->u_game($request, $selectUGame, $start_time, $end_time, $group_day);
			$stats_u_sign = $this->u_sign($request, $selectUSign, $start_time, $end_time, $group_day);
		}


		//3.新增游戏人数
		$query = User::query();
		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【时间】
		$this->makeWhereParamDatetimeTimeZone1($request, $query, 'first_game_time','datetime', $start_time, $end_time);
		// 查询数据
		$stats_nu_game = $query->selectRaw(implode(',', [
			$selectNuGame,
			'COUNT(*) as nu_game',
		]))
			->groupBy('timed')
			->orderBy('timed')
			->get();

		//4.注册人数
		$query = User::query();
		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【时间】
		$this->makeWhereParamDatetimeTimeZone1($request, $query, 'registration_time','datetime', $start_time, $end_time);
		// 查询数据
		$stats_nu_sign = $query->selectRaw(implode(',', [
			$selectNuSign,
			'COUNT(*) as nu_sign',
		]))
			->groupBy('timed')
			->orderBy('timed')
			->get();

		date_default_timezone_set(Timed::getTimezoneName());
		//转换指定时区
		if($group_day != 'week'){
			$stats_nu_game->transform(function ($item)use($request) {
				$item['timed_str'] = $item['timed'];
				$item['timed'] = strtotime($item['timed']);
				return $item;
			});
			$stats_nu_sign->transform(function ($item)use($request) {
				$item['timed_str'] = $item['timed'];
				$item['timed'] = strtotime($item['timed']);
				return $item;
			});

		}

		$stats_nu_game = $stats_nu_game->toArray();
		$stats_nu_sign = $stats_nu_sign->toArray();

		$stats_u_game = array_column($stats_u_game, 'u_game', 'timed');
		$stats_u_sign = array_column($stats_u_sign, 'u_sign', 'timed');
		$stats_nu_game = array_column($stats_nu_game, 'nu_game', 'timed');
		$stats_nu_sign = array_column($stats_nu_sign, 'nu_sign', 'timed');

		return [
			'stats' =>[
				'u_game' => $stats_u_game,
				'u_sign' => $stats_u_sign,
				'nu_game' => $stats_nu_game,
				'nu_sign' => $stats_nu_sign,
			],
		];

	}

	public function u_game($request, $selectUGame, $start_time, $end_time, $group_day='day'){
		//1.游戏人数
		$query = Info::query();
		$query->where('status', Info::STATUS_NORMAL)->where('player_type', Info::PLAYER_TYPE);
		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【时间】
		$this->makeWhereParamDatetimeTimeZone($request, $query, 'end_time','datetime', $start_time, $end_time);
		$stats_u_game = $query->selectRaw(implode(',', [
			$selectUGame,
			'COUNT(DISTINCT uid) as u_game',
		]))
			->groupBy('timed')
			->orderBy('timed')
			->get();
//        Timed::toSql($stats_u_game);

		//转换指定时区
		date_default_timezone_set($request->user()->config->timezone);

		$stats_u_game->transform(function ($item)use($group_day) {

			if($group_day != 'week'){
				$item['timed'] = strtotime($item['timed']);
			}

			return $item;
		});

		return $stats_u_game->toArray();
	}
	public function u_sign($request, $selectUSign, $start_time, $end_time, $group_day='day'){
		//2.登录人数
		$query = UserLogin::query();
		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【时间】
		$this->makeWhereParamDatetimeTimeZone($request, $query, 'login_time','datetime', $start_time, $end_time);
		// 查询数据
		$stats_u_sign = $query->selectRaw(implode(',', [
			$selectUSign,
			'COUNT(DISTINCT uid) as u_sign',
		]))
			->groupBy('timed')
			->orderBy('timed')
			->get();

		//转换指定时区
		date_default_timezone_set($request->user()->config->timezone);

		$stats_u_sign->transform(function ($item)use($group_day) {

			if($group_day != 'week'){
				$item['timed'] = strtotime($item['timed']);
			}

			return $item;
		});

		return $stats_u_sign->toArray();
	}
}
